//
//  LCNewFeatureView.swift
//  SwiftWeiBo
//
//  Created by LiCheng on 2017/2/15.
//  Copyright © 2017年 LiCheng. All rights reserved.
//

import UIKit

/// 新特性视图
class LCNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterBtn: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!


    /// 类方法，创建视图
    class func newFeatureView() -> LCNewFeatureView {

        let nib = UINib.init(nibName: "LCNewFeatureView", bundle: nil)

        // .first
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! LCNewFeatureView

        // 视图大小
        // - 从 xib 加载的视图，默认是 600 * 600
        view.frame = UIScreen.main.bounds

        return view
    }

    /// xib 加载完成调用
    override func awakeFromNib() {


        // 1. 添加 图像
        let count = 4
        let rect = UIScreen.main.bounds

        for i in 0..<count {
            let imageName = "new_feature_\(i+1)"
            let imgView = UIImageView(image: UIImage(named: imageName))

            // 设置 frame
            imgView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)

            scrollView.addSubview(imgView)
        }

        // 2. scrollView 属性
        //    - +1 是为了滚动到末尾直接显示首页
        scrollView.contentSize = CGSize(width: CGFloat(count+1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.delegate = self

        // 3. 隐藏按钮
        enterBtn.isHidden = true

        // 4. 禁止点击 pageControl
        pageControl.isUserInteractionEnabled = false

    }

    @IBAction func enterClick() {

        removeFromSuperview()
    }
}

// MARK: - UIScrollViewDelegate
extension LCNewFeatureView: UIScrollViewDelegate {

    /// 减速时 调用
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        // 1. 滚到到最后一屏 删除视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }

        // 2. 如果是倒数第二页， 显示按钮
        if page == scrollView.subviews.count - 1 {
            enterBtn.isHidden = false
        }else{
            enterBtn.isHidden = true
        }
    }


    /// 滚动视图一滚动就会调用
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        // 1. 一旦滚动隐藏按钮
        enterBtn.isHidden = true

        // 2. 计算当前偏移量
        //    - 0.5 滚动超出半屏是改变
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)

        // 3. 设置分页控件
        pageControl.currentPage = page

        // 4. 分页控件隐藏
        if page == scrollView.subviews.count {
            pageControl.isHidden = true
        }else{
            pageControl.isHidden = false
        }
    }
}
